/**
 * Created by HP on 2017/10/17.
 */
var mongoose = require('mongoose');
//引入数据模型
const DataModel = require('../models/commemt.model');


//增删改查
//增加
exports.create = function (req,res,next) {
	const  dataModel = new DataModel(req.body);
	//
	
	dataModel.save()
		.then(data=>{
			res.json(data);
		})
	
}
//获取一条
exports.get = function (req,res,next) {
	var id = req.params.id;
	DataModel.findById(id, function (err, data) {
		res.json(data);
	})
}

//修改
exports.update = function (req,res,next) {
	var id = req.params.id;
	DataModel.findByIdAndUpdate(id, {$set:req.body}, {new:false})
		.then(data=>{
			res.json(data)
		})
}

//删除
exports.remove = function (req,res,next) {
	const id = req.params.id;
	DataModel.findByIdAndRemove(id,function (err,data) {
		res.json(data);
	})
}
//分页查询
exports.list = function (req,res,next) {
	var page = (req.body.page)?req.body.page:1;
	var rows = (req.body.rows)?req.body.rows:10;
	// console.log(rows);
	var queryCondition={}//查询条件
	
	if(req.body.cateId && req.body.cateId.trim().length>0){
		cateId = req.body.cateId;
		queryCondition={
			"cateId":cateId
		}
	}
	// console.log({page:page,limit:limit});
	DataModel.paginate(queryCondition, {sort: { _id: -1 }, page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
		
		result.rows = result.docs;
		delete result.docs;
		res.json(result);
	});
	
}

//删除多个
exports.deletes = function (req,res,next) {
	var ids = req.body.ids; //字符串
	console.log(ids.split(',').length>0);
	if(ids.length>0){
		DataModel.remove({_id:{$in:ids.split(',')}})
			.then(data=>{
			res.json({"msg":"deletes success","status":200});
		})
	}else{
		res.json({"msg":"deletes fail","status":404});
	}
}